//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package cfca.seal.front.service.ws.impl;

import cfca.com.itextpdf.text.Rectangle;
import cfca.com.itextpdf.text.pdf.PdfReader;
import cfca.sadk.util.Base64;
import cfca.seal.bean.OperationLog;
import cfca.seal.dao.main.IOperationLogDao;
import cfca.seal.exception.CodeException;
import cfca.seal.front.service.FunctionType;
import cfca.seal.front.service.ws.IBusinessSealService;
import cfca.seal.front.service.ws.bean.AddBlankSignatureBean;
import cfca.seal.front.service.ws.util.ValidityUtil;
import cfca.seal.mananger.OperationLogManager;
import cfca.seal.sadk.DonePdfSealUtil;
import cfca.seal.system.Env;
import cfca.seal.util.FileUtil;
import cfca.seal.util.PDFFieldXMLUtil;
import cfca.seal.util.StringUtil;
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BusinessSealServiceImpl implements IBusinessSealService {
  private static final Logger log = LoggerFactory.getLogger("service_sys");
  private static final String FILE_TYPE_HTML = "html";
  private static final String FILE_TYPE_HTML2 = "html2";
  private static final String FILE_TYPE_WORD = "word";
  @Resource
  IOperationLogDao operationLogDao;

  public BusinessSealServiceImpl() {
  }

  public byte[] synthesizeAutoBusinessPdf(byte[] pdf, String fieldListXML, String imageListXML) {
    log.info("PDF业务数据自动化合成开始");
    log.info("需要合成到pdf文本域的业务数据:" + fieldListXML);
    log.info("需要合成到pdf的图片数据:" + imageListXML);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.synthesizeAutoBusinessPdf.toString(), "PDF业务数据自动化合成");
    byte[] pdfFileData = null;

    byte[] var7;
    try {
      if (null == pdf || pdf.length == 0) {
        throw new CodeException("C3007", "PDF文档不能为空");
      }

      pdfFileData = PDFFieldXMLUtil.synthesizeAutoBusinessPdf(pdf, fieldListXML, imageListXML);
      log.info("PDF业务数据自动化合成结束");
      return pdfFileData;
    } catch (CodeException var16) {
      CodeException ce = var16;
      operationLog.setResult(10);
      log.error("接口在进行PDF合成发生失败! ", var16);

      try {
        var7 = ("<Error><ErrorCode>" + ce.getCode() + "</ErrorCode><ErrorMessage>" + ce.getMessage() + "</ErrorMessage></Error>").getBytes("UTF-8");
        return var7;
      } catch (Exception var14) {
        var14.printStackTrace();
        return pdfFileData;
      }
    } catch (Exception var17) {
      operationLog.setResult(10);
      log.error("接口在进行PDF合成发生失败! ", var17);

      try {
        var7 = "<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>PDF合成发生系统异常</ErrorMessage></Error>".getBytes("UTF-8");
      } catch (Exception var15) {
        var15.printStackTrace();
        return pdfFileData;
      }
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return var7;
  }

  public byte[] transformToPdf(byte[] source, String fileType) {
    log.info("转换Pdf开始");
    log.info("转换Pdf文件类型:" + fileType);
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.transformToPdf.toString(), "转换Pdf");
    byte[] pdfResult = "".getBytes();

    byte[] var6;
    try {
      if (null == source || source.length == 0) {
        throw new CodeException("C3044", "待转PDF文档的源文件不能为空");
      }

      if (StringUtil.isEmpty(fileType)) {
        throw new CodeException("C3042", "文件类型没有输入");
      }

      ByteArrayOutputStream baos;
      if ("html".equalsIgnoreCase(fileType)) {
        baos = new ByteArrayOutputStream();
        ITextRenderer renderer = new ITextRenderer();
        ITextFontResolver fontResolver = renderer.getFontResolver();
        String fontPath = Env.configDir + File.separator + "fonts" + File.separator + "simsun.ttc";
        fontResolver.addFont(fontPath, "Identity-H", false);
        renderer.setDocumentFromString(new String(source, "UTF-8"));
        renderer.layout();
        renderer.createPDF(baos);
        pdfResult = baos.toByteArray();
      } else {
        OpenOfficeDocumentConverter converter;
        ByteArrayInputStream byteArrayInputStream;
        ByteArrayOutputStream byteArrayOutputStream;
        DefaultDocumentFormatRegistry formatReg;
        DocumentFormat html;
        DocumentFormat pdf2;
        SocketOpenOfficeConnection connection;
        if ("word".equalsIgnoreCase(fileType)) {
          formatReg = new DefaultDocumentFormatRegistry();
          pdf2 = formatReg.getFormatByFileExtension("pdf");
          html = formatReg.getFormatByFileExtension("doc");
          connection = new SocketOpenOfficeConnection(Env.openOfficeIP, Integer.valueOf(Env.openOfficePort));
          connection.connect();
          converter = new OpenOfficeDocumentConverter(connection);
          byteArrayInputStream = new ByteArrayInputStream(source);
          byteArrayOutputStream = new ByteArrayOutputStream();
          converter.convert(byteArrayInputStream, html, byteArrayOutputStream, pdf2);
          pdfResult = byteArrayOutputStream.toByteArray();
          if (connection != null) {
            connection.disconnect();
          }
        } else {
          if (!"html2".equalsIgnoreCase(fileType)) {
            throw new CodeException("C3045", "文件类型不正确(目前只支持html/word/html2类型)");
          }

          formatReg = new DefaultDocumentFormatRegistry();
          pdf2 = formatReg.getFormatByFileExtension("pdf");
          html = formatReg.getFormatByFileExtension("html");
          connection = new SocketOpenOfficeConnection(Env.openOfficeIP, Integer.valueOf(Env.openOfficePort));
          connection.connect();
          converter = new OpenOfficeDocumentConverter(connection);
          byteArrayInputStream = new ByteArrayInputStream(source);
          byteArrayOutputStream = new ByteArrayOutputStream();
          converter.convert(byteArrayInputStream, html, byteArrayOutputStream, pdf2);
          pdfResult = byteArrayOutputStream.toByteArray();
          if (connection != null) {
            connection.disconnect();
          }
        }
      }

      baos = new ByteArrayOutputStream();
      addPagination(pdfResult, baos);
      pdfResult = baos.toByteArray();
      log.info("转换Pdf结束");
      return pdfResult;
    } catch (CodeException var20) {
      CodeException ce = var20;
      operationLog.setResult(10);
      log.error("接口在进行转换Pdf发生失败! ", var20);

      try {
        var6 = ("<Error><ErrorCode>" + ce.getCode() + "</ErrorCode><ErrorMessage>" + ce.getMessage() + "</ErrorMessage></Error>").getBytes("UTF-8");
        return var6;
      } catch (UnsupportedEncodingException var18) {
        var18.printStackTrace();
        return pdfResult;
      }
    } catch (Exception var21) {
      Exception e = var21;
      operationLog.setResult(10);
      log.error("接口在进行转换Pdf发生异常! ", var21);

      try {
        if (!e.getMessage().contains("must be terminated by the matching end-tag")) {
          if (e.getMessage().contains("Can't load the XML resource (using TRaX transformer)")) {
            var6 = "<Error><ErrorCode>C3077</ErrorCode><ErrorMessage>HTML文件内容中存在属性书写不正确的标签</ErrorMessage></Error>".getBytes("UTF-8");
            return var6;
          }

          var6 = "<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>转换Pdf发生错误</ErrorMessage></Error>".getBytes("UTF-8");
          return var6;
        }

        var6 = "<Error><ErrorCode>C3069</ErrorCode><ErrorMessage>HTML文档存在没有匹配的结束标签</ErrorMessage></Error>".getBytes("UTF-8");
      } catch (UnsupportedEncodingException var19) {
        var19.printStackTrace();
        return pdfResult;
      }
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return var6;
  }

  public byte[] autoConcatPdfs(byte[] pdf1, byte[] pdf2) {
    log.info("合并PDF开始");
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.transformToPdf.toString(), "合并PDF");
    byte[] pdf = "".getBytes();

    try {
      byte[] var6;
      try {
        if (null == pdf1 || pdf1.length == 0 || null == pdf2 || pdf2.length == 0) {
          throw new CodeException("C3007", "PDF文档不能为空");
        }

        pdf = DonePdfSealUtil.concatenatePdfs(new PdfReader[]{new PdfReader(pdf1), new PdfReader(pdf2)}, true);
        log.info("合并PDF结束");
      } catch (CodeException var15) {
        CodeException ce = var15;
        operationLog.setResult(10);
        log.error("接口在进行合并PDF发生异常! ", var15);

        try {
          var6 = ("<Error><ErrorCode>" + ce.getCode() + "</ErrorCode><ErrorMessage>" + ce.getMessage() + "</ErrorMessage></Error>").getBytes("UTF-8");
          return var6;
        } catch (UnsupportedEncodingException var14) {
          var14.printStackTrace();
        }
      } catch (Exception var16) {
        operationLog.setResult(10);
        log.error("接口在进行合并PDF发生异常! ", var16);

        try {
          var6 = "<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>接口在进行合并PDF发生异常</ErrorMessage></Error>".getBytes("UTF-8");
          return var6;
        } catch (UnsupportedEncodingException var13) {
          var13.printStackTrace();
        }
      }
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return pdf;
  }

  public String autoConcatPdfList(String pdfBase64List, String outputFilePath) {
    log.info("合并PDF列表开始");
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.transformToPdf.toString(), "合并PDF");
    String concatPdfBase64 = "";

    String var6;
    try {
      if (StringUtil.isEmpty(pdfBase64List)) {
        throw new CodeException("C3007", "PDF文档不能为空");
      }

      List<String> pdfList = new ArrayList();
      StringUtil.getNodesText(pdfBase64List, "Pdf", pdfList);
      if (null == pdfList || pdfList.size() == 0) {
        throw new CodeException("C3007", "PDF文档不能为空");
      }

      PdfReader[] reader = new PdfReader[pdfList.size()];

      for(int i = 0; i < pdfList.size(); ++i) {
        String pdfBase64 = (String)pdfList.get(i);
        if (StringUtil.isNotEmpty(pdfBase64)) {
          if (pdfBase64.getBytes().length < 500) {
            byte[] pdfBytes = "".getBytes();

            try {
              FileInputStream stream = new FileInputStream(new File(pdfBase64));
              pdfBytes = FileUtil.getBytesFromInputStream(stream);
            } catch (Exception var16) {
              throw new CodeException("C3068", "文件不存在" + pdfBase64);
            }

            reader[i] = new PdfReader(pdfBytes);
          } else {
            reader[i] = new PdfReader(Base64.decode(pdfBase64));
          }
        }
      }

      byte[] pdf = DonePdfSealUtil.concatenatePdfs(reader, true);
      concatPdfBase64 = Base64.toBase64String(pdf);
      if (StringUtil.isNotEmpty(outputFilePath)) {
        FileUtil.saveDataToFile(pdf, outputFilePath);
        log.info("合成后文档存储位置：" + outputFilePath);
      }

      log.info("合并PDF列表结束");
      return "<Result><Code>200</Code><Message>successfully!</Message><Pdf>" + concatPdfBase64 + "</Pdf></Result>";
    } catch (CodeException var17) {
      operationLog.setResult(10);
      log.error("接口在进行合并PDF列表发生异常! ", var17);
      var6 = "<Result><Code>" + var17.getCode() + "</Code><Message>" + var17.getMessage() + "</Message></Result>";
      return var6;
    } catch (Exception var18) {
      operationLog.setResult(10);
      log.error("接口在进行合并PDF列表发生异常! ", var18);
      var6 = "<Result><Code>C0001</Code><Message>接口在进行合并PDF列表发生异常</Message></Result>";
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return var6;
  }

  public static void addPagination(byte[] pdf, OutputStream outputStream) {
    Document document = new Document();

    try {
      com.lowagie.text.pdf.PdfReader pdfReader = new com.lowagie.text.pdf.PdfReader(pdf);
      PdfWriter writer = PdfWriter.getInstance(document, outputStream);
      document.open();
      BaseFont bf = BaseFont.createFont("Helvetica", "Cp1252", false);
      PdfContentByte cb = writer.getDirectContent();
      int currentPageNumber = 0;
      int pageOfCurrentReaderPDF = 0;

      while(pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
        document.newPage();
        ++pageOfCurrentReaderPDF;
        ++currentPageNumber;
        PdfImportedPage page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
        cb.addTemplate(page, 0.0F, 0.0F);
        cb.beginText();
        cb.setFontAndSize(bf, 15.0F);
        cb.showTextAligned(1, "" + currentPageNumber, Float.parseFloat((double)pdfReader.getPageSize(currentPageNumber).getWidth() * 0.9D + ""), Float.parseFloat((double)pdfReader.getPageSize(currentPageNumber).getHeight() * 0.006D + ""), 0.0F);
        cb.endText();
      }

      outputStream.flush();
      document.close();
      outputStream.close();
    } catch (Exception var18) {
      var18.printStackTrace();
    } finally {
      if (document.isOpen()) {
        document.close();
      }

      try {
        if (outputStream != null) {
          outputStream.close();
        }
      } catch (IOException var17) {
        var17.printStackTrace();
      }

    }

  }

  public byte[] addBlankSignature2Pdf(byte[] pdf, String blankSignatureStrategyXML) {
    OperationLog operationLog = OperationLogManager.getInstance(FunctionType.addBlankSignature2Pdf.toString(), "PDF添加空白签名域");
    new String();
    log.info("PDF添加空白签名域开始");
    log.info("PDF添加空白签名域策略文件:" + blankSignatureStrategyXML);

    try {
      String errorResult;
      byte[] var6;
      try {
        if (null == pdf || pdf.length == 0) {
          throw new CodeException("C3007", "PDF文档不能为空");
        }

        List<String> nodes = new ArrayList();
        StringUtil.getNodesText(blankSignatureStrategyXML, "BlankSignature", nodes);
        PdfReader reader = new PdfReader(pdf);
        Iterator i$ = nodes.iterator();

        while(true) {
          if (!i$.hasNext()) {
            log.info("PDF添加空白签名域结束");
            break;
          }

          String xml = (String)i$.next();
          AddBlankSignatureBean addBlankSignatue = new AddBlankSignatureBean(xml);
          ValidityUtil.checkParamForAddBlankSignature2Pdf(addBlankSignatue, reader.getNumberOfPages());
          Rectangle rectangle = new Rectangle(Float.parseFloat(addBlankSignatue.getLx()), Float.parseFloat(addBlankSignatue.getLy()), Float.parseFloat(addBlankSignatue.getLx()) + Float.parseFloat(addBlankSignatue.getWidth()), Float.parseFloat(addBlankSignatue.getLy()) + Float.parseFloat(addBlankSignatue.getHeight()));
          pdf = DonePdfSealUtil.createBlankSignature(reader, Integer.parseInt(addBlankSignatue.getPage()), rectangle, addBlankSignatue.getFieldName());
          reader = new PdfReader(pdf);
        }
      } catch (CodeException var19) {
        operationLog.setResult(10);
        log.error("WebService接口在进行PDF添加空白签名域发生失败! " + blankSignatureStrategyXML, var19);
        errorResult = "<Error><ErrorCode>" + var19.getCode() + "</ErrorCode><ErrorMessage>" + var19.getMessage() + "</ErrorMessage></Error>";

        try {
          var6 = errorResult.getBytes("UTF-8");
          return var6;
        } catch (Exception var18) {
          var18.printStackTrace();
        }
      } catch (Exception var20) {
        operationLog.setResult(10);
        log.error("WebService接口在进行PDF添加空白签名域发生失败! " + blankSignatureStrategyXML, var20);
        errorResult = "<Error><ErrorCode>C0001</ErrorCode><ErrorMessage>PDF添加空白签名域发生异常</ErrorMessage></Error>";

        try {
          var6 = errorResult.getBytes("UTF-8");
          return var6;
        } catch (Exception var17) {
          var17.printStackTrace();
        }
      }
    } finally {
      this.operationLogDao.insert(operationLog);
    }

    return pdf;
  }
}
